package com.czy.seed.mvc.home.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.service.impl.BaseServiceImpl;
import com.czy.seed.mvc.home.controller.PurchaseController;
import com.czy.seed.mvc.home.entity.*;
import com.czy.seed.mvc.home.mapper.*;
import com.czy.seed.mvc.home.service.CommodityService;
import com.czy.seed.mvc.home.service.MenuService;
import com.czy.seed.mvc.home.service.PurchaseDetailedListService;
import com.czy.seed.mvc.home.service.PurchaseOrdersService;
import com.czy.seed.mvc.sys.service.SysUserService;
import com.czy.seed.mvc.util.ManageSendMessage;
import com.czy.seed.mvc.util.PrincipalUtil;
import com.czy.seed.mvc.util.SystemProperties;
import com.czy.seed.mybatis.base.QueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PurchaseOrdersServiceImpl extends BaseServiceImpl<PurchaseOrders> implements PurchaseOrdersService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private BeginningBudgetMapper beginningBudgetMapper;

    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;

    @Autowired
    private PurchaseDetailedListMapper purchaseDetailedListMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private CommodityService commodityService;
    @Autowired
    private PurchaseOrdersService purchaseOrdersService;
    @Autowired
    private PurchaseDetailedListService purchaseDetailedListService;
    @Autowired
    private MenuService menuServic;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    SystemProperties systemProperties;
    public static Logger logger = LoggerFactory.getLogger(PurchaseController.class);

    @Override
    public List<PurchaseOrders> selectpurchaseOrdersByCreateUser(String type, long c_id) {

        return purchaseOrdersMapper.selectpurchaseOrdersByCreateUser(type, c_id);
    }

    @Override
    public List<PurchaseOrders> selectpurchaseOrdersByCreateUser_(int type, Long userId, String types) {

        return purchaseOrdersMapper.selectpurchaseOrdersByCreateUser_(type, userId, types);
    }


    @Override
    public List<PurchaseOrders> selectMemorandInUniting(Long merchantId, Long userId) {

        return purchaseOrdersMapper.selectMemorandInUniting(merchantId, userId);
    }


    @Override
    public List<PurchaseOrders> selectpurchaseOrdersByUserbycreate(long userId, String type) {
        return purchaseOrdersMapper.selectpurchaseOrdersByUserbycreate(userId, type);
    }

    @Override
    public List<PurchaseOrderDetailVo> selectmemorInUniting(Long P_orderId) {
        return purchaseOrdersMapper.selectmemorInUniting(P_orderId);

    }

    @Override
    public Map<String, Object> createMemorandInUniting_impl(String type, long ordersid, String fileName, String r_path, long purchaseid, String path) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            purchaseDetailedListService.updateByParentId_m(type, ordersid, fileName, r_path, PrincipalUtil.getLoginUser().getId());
            //根据子单与主单关联关系处理主单，如果查出来所有子单全部为结果确认，则将该主单类型置为结果确认，该状态意味着前台页面可以打印确认单
            QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("ssdd_glgx", purchaseid);
            criteria.andEqualTo("type", "待完成");
            List<PurchaseDetailedList> List = purchaseDetailedListService.selectListByParams(queryParams);
            queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria2 = queryParams.createCriteria();
            criteria2.andEqualTo("ssdd_glgx", purchaseid);
            List<PurchaseDetailedList> List1 = purchaseDetailedListService.selectListByParams(queryParams);
            if (List.size() == List1.size()) {
                QueryParams queryParams1 = new QueryParams(PurchaseOrders.class);
                QueryParams.Criteria criteria1 = queryParams1.createCriteria();
                criteria1.andEqualTo("id", purchaseid);
                List<PurchaseOrders> ls = purchaseOrdersService.selectListByParams(queryParams1);
                PurchaseOrders lls = ls.get(0);
                lls.setType("待完成");
                lls.setUpdatetime(new Date());
                lls.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
                purchaseOrdersService.updateByPrimaryKey(lls);
            }
            pageInfo.put("fileName", fileName);
            pageInfo.put("path", path);
        } catch (Exception e) {
            logger.error("初始化合同失败", e);
        }
        return pageInfo;


    }

    @Override
    public Map<String, Object> createOrdersValidation_impl(String type, long id, String fileName, String paths, PurchaseOrderDetailVo purchaseOrderDetailVo, String path) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            purchaseDetailedListService.updateByParentId_(type, id, fileName, paths, PrincipalUtil.getLoginUser().getId());
            //根据子单与主单关联关系处理主单，如果查出来所有子单全部为结果确认，则将该主单类型置为结果确认，该状态意味着前台页面可以打印确认单
            QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("ssdd_glgx", purchaseOrderDetailVo.getId());
            criteria.andEqualTo("type", "等待确认单");
            List<PurchaseDetailedList> List = purchaseDetailedListService.selectListByParams(queryParams);

            queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria2 = queryParams.createCriteria();
            criteria2.andEqualTo("ssdd_glgx", purchaseOrderDetailVo.getId());
            List<PurchaseDetailedList> List1 = purchaseDetailedListService.selectListByParams(queryParams);

            if (List.size() > List1.size()) {
                QueryParams queryParams1 = new QueryParams(PurchaseOrders.class);
                QueryParams.Criteria criteria1 = queryParams1.createCriteria();
                criteria1.andEqualTo("id", purchaseOrderDetailVo.getId());
                List<PurchaseOrders> ls = purchaseOrdersService.selectListByParams(queryParams1);
                PurchaseOrders lls = ls.get(0);
                lls.setType("等待确认单");
                lls.setUpdatetime(new Date());
                lls.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
                purchaseOrdersService.updateByPrimaryKey(lls);
            }
            pageInfo.put("fileName", fileName);
            pageInfo.put("path", path);
        } catch (Exception e) {
            logger.error("初始化确认单失败", e);
        }
        return pageInfo;
    }

    /**
     * 采购办 审核采购单位提交的采购单信息
     *
     * @param request
     * @param secondInquirySwitch
     * @return
     */

    @Override
    public Map<String, Object> toCenterDetailByParentId_impl(HttpServletRequest request, String secondInquirySwitch) {
        Map<String, Object> pageInfo = new HashMap<>(16);
        try {
            String parentobject = request.getParameter("parentData");
            String object = request.getParameter("data");
            String type = request.getParameter("type");
            PurchaseOrders purchaseOrders = JSONObject.parseObject(parentobject, PurchaseOrders.class);
            purchaseOrders.setType(type);
            purchaseOrders.setUpdatetime(new Date());
            purchaseOrders.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
            purchaseOrders.setSzfcgbgsjbr(PrincipalUtil.getLoginUser().getUsername());
            purchaseOrders.setSzfcgbsjfzr(PrincipalUtil.getLoginUser().getUsername());
            purchaseOrders.setSzfcgbsjfzrqmsj(new Date());
            //查看采购人的年初预算
            if ("审核不通过".equals(type)) {
                type = "申请";
            }
            if ("Y".equals(secondInquirySwitch) && !"审核不通过".equals(type)) {
                QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
                QueryParams.Criteria criteria = queryParams.createCriteria();
                criteria.andEqualTo("ssdd_glgx", purchaseOrders.getId());
                PurchaseDetailedList purchaseDetailedList = new PurchaseDetailedList();
                purchaseDetailedList.setType("结果确认");
                purchaseDetailedList.setGmfs("直接购买");
                purchaseDetailedList.setUpdatetime(new Date());
                purchaseDetailedList.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
                int i = purchaseDetailedListService.updateSelectiveByParams(purchaseDetailedList, queryParams);
                purchaseOrders.setType("结果确认");
                purchaseOrdersService.updateByPrimaryKey(purchaseOrders);
                //修改年初预算信息
                modifyEarlyBudget(purchaseOrders.getCreator_userid(), "--", new BigDecimal(purchaseOrders.getBhdget_amount()));
                ManageSendMessage manageSendMessage = new ManageSendMessage();
                manageSendMessage.queryMessage("采购单位", PrincipalUtil.getLoginUser().getId(), "您有一个采购单审核通过，请您尽快处理！", sysUserService, systemProperties);
                pageInfo.put("status", "true");
                return pageInfo;
            }
            //先取到主单信息
            purchaseOrdersService.updateByPrimaryKey(purchaseOrders);
            //增加子单
            purchaseDetailedListService.updateByParentId(type, purchaseOrders.getId(), PrincipalUtil.getLoginUser().getId());
            String context = purchaseOrders.getEntry_name() + "向您提交了一个新的采购单，请您尽快审阅审批！";
            if ("申请".equals(type)) {
                //发送短信
                context = "您有一个采购单被退回，请您尽快处理！";
                ManageSendMessage manageSendMessage = new ManageSendMessage();
                manageSendMessage.queryMessage("采购单位", PrincipalUtil.getLoginUser().getId(), context, sysUserService, systemProperties);
            } else {
                modifyEarlyBudget(purchaseOrders.getCreator_userid(), "--", new BigDecimal(purchaseOrders.getBhdget_amount()));
                context = "您有一个采购单审核通过，请您尽快处理！";
                ManageSendMessage manageSendMessage = new ManageSendMessage();
                manageSendMessage.queryMessage("采购单位", PrincipalUtil.getLoginUser().getId(), context, sysUserService, systemProperties);
            }
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("采购办审核采购单失败.", e);
        }
        return pageInfo;
    }

    @Override
    public Map<String, Object> insertDetailAndAddOrders4Frist_impl(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<>(16);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String object = request.getParameter("data");
        //创建主单
        PurchaseOrders purchaseOrders = new PurchaseOrders();
        purchaseOrders.setType("申请");
        purchaseOrders.setCreatetime(new Date());
        purchaseOrders.setCreator_userid(PrincipalUtil.getLoginUser().getId());
        if (PrincipalUtil.getLoginUser().getName() != null) {
            purchaseOrders.setCompany_name(PrincipalUtil.getLoginUser().getName());
        }
        purchaseOrders.setLxr(PrincipalUtil.getLoginUser().getUsername());
        purchaseOrders.setPhone(PrincipalUtil.getLoginUser().getTelephone());
        purchaseOrders.setCreatetime(new Date());
        //初始化主单 收入块数据
        purchaseOrders.setCzbksr(0);
        purchaseOrders.setYsxzsysf(0);
        purchaseOrders.setYszfxjj(0);
        purchaseOrders.setYsqtzffssr(0);
        purchaseOrders.setYsqtzffssr(0);
        purchaseOrders.setCzzhggfsssr(0);
        purchaseOrders.setSjczzyzf(0);
        purchaseOrders.setSysr(0);
        purchaseOrders.setYysr(0);
        purchaseOrders.setSjbzsr(0);
        purchaseOrders.setFsdwsjsr(0);
        purchaseOrders.setQtsr(0);
        try {
            purchaseOrdersService.insert(purchaseOrders);
            long f_id = purchaseOrders.getId();
            //拿到子单实体并创建子单
            PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
            purchaseDetailedList.setType("申请");
            purchaseDetailedList.setCreatetime(new Date());
            purchaseDetailedList.setSsdd_glgx(f_id);
            purchaseDetailedList.setCreateuserid(PrincipalUtil.getLoginUser().getId());
            purchaseDetailedListService.insert(purchaseDetailedList);
            String id = String.valueOf(purchaseDetailedList.getId());
            pageInfo.put("f_id", f_id);
            pageInfo.put("id", id);
            pageInfo.put("status", "true");
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("创建采购清单失败", e);
        }
        return pageInfo;

    }

    @Override
    @Transactional
    public Map<String, Object> addDetailByParentId_impl(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<>(16);
        String parentobject = request.getParameter("parentData");
        String object = request.getParameter("data");
        //先取到主单信息
        PurchaseOrders purchaseOrders = JSONObject.parseObject(parentobject, PurchaseOrders.class);
        long parentId = purchaseOrders.getId();
        //增加子单
        PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
        purchaseDetailedList.setType("申请");
        purchaseDetailedList.setCreatetime(new Date());
        purchaseDetailedList.setSsdd_glgx(parentId);
        purchaseDetailedList.setCreateuserid(PrincipalUtil.getLoginUser().getId());
        try {
            purchaseOrders.setBhdget_amount(purchaseOrders.getBhdget_amount() + purchaseDetailedList.getZj());
            purchaseDetailedListService.insert(purchaseDetailedList);
            int i = purchaseOrdersService.updateSelectiveByPrimaryKey(purchaseOrders);
            String id = String.valueOf(purchaseDetailedList.getId());
            pageInfo.put("purchaseOrders", purchaseOrders);
            pageInfo.put("parentId", String.valueOf(parentId));
            pageInfo.put("id", id);
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("新增清单失败", e);
        }
        return pageInfo;

    }

    @Override
    public Map<String, String> updateDetailById_impl(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<>(16);
        String object = request.getParameter("data");
        //更新子单
        PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
        purchaseDetailedList.setUpdatetime(new Date());
        purchaseDetailedList.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
        try {
            purchaseDetailedListService.updateByPrimaryKey(purchaseDetailedList);
            String id = String.valueOf(purchaseDetailedList.getId());
            pageInfo.put("status", "true");
            pageInfo.put("f_id", String.valueOf(purchaseDetailedList.getSsdd_glgx()));
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("更新清单信息失败", e);
        }
        return pageInfo;

    }

    @Override
    public Map<String, String> deleteDetailById_impl(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<>(16);
        String object = request.getParameter("data");
        String orderId = request.getParameter("order");
        //更新子单
        try {
            PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
            PurchaseOrders purchaseOrders = JSONObject.parseObject(orderId, PurchaseOrders.class);
            purchaseOrders.setBhdget_amount(purchaseOrders.getBhdget_amount() - purchaseDetailedList.getZj());
            purchaseDetailedListService.deleteByPrimaryKey(purchaseDetailedList.getId());
            purchaseOrdersService.updateSelectiveByPrimaryKey(purchaseOrders);
            pageInfo.put("status", "true");
            pageInfo.put("bhdget_amount", purchaseOrders.getBhdget_amount() + "");
        } catch (Exception e) {
            logger.error("删除清单信息失败", e);

        }
        return pageInfo;

    }

    /**
     * 不会二次询价直接购买商品信息
     *
     * @param type
     * @param purchaseDetailedList
     * @return
     */

    @Override
    @Transactional
    public Map<String, String> updateDetailById4type_impl(String type, PurchaseDetailedList purchaseDetailedList) {
        Map<String, String> pageInfo = new HashMap<>(16);
        purchaseDetailedList.setType(type);
        purchaseDetailedList.setGmfs("直接购买");
        purchaseDetailedList.setUpdatetime(new Date());
        purchaseDetailedList.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
        try {
            purchaseDetailedListService.updateByPrimaryKey(purchaseDetailedList);
            //根据子单与主单关联关系处理主单，如果查出来所有子单全部为结果确认，则将该主单类型置为结果确认，该状态意味着前台页面可以打印确认单
            QueryParams queryParams1 = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria1 = queryParams1.createCriteria();
            criteria1.andEqualTo("ssdd_glgx", purchaseDetailedList.getSsdd_glgx());
            List<PurchaseDetailedList> List1 = purchaseDetailedListService.selectListByParams(queryParams1);
            QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("ssdd_glgx", purchaseDetailedList.getSsdd_glgx());
            criteria.andEqualTo("type", "结果确认");
            List<PurchaseDetailedList> List = purchaseDetailedListService.selectListByParams(queryParams);
            if (List.size() == List1.size()) {
                PurchaseOrders purchaseOrders = purchaseOrdersService.selectByPrimaryKey(purchaseDetailedList.getSsdd_glgx());
                purchaseOrders.setType("结果确认");
                purchaseOrders.setUpdatetime(new Date());
                purchaseOrders.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
                purchaseOrdersService.updateByPrimaryKey(purchaseOrders);
            }
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("更新清单状态失败", e);
        }
        return pageInfo;

    }

    @Override
    public Map<String, String> updateDetailtype_impl(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<>(16);
        String object = request.getParameter("data");
        String type = request.getParameter("type");
        //更新子单
        PurchaseDetailedList purchaseDetailedList = JSONObject.parseObject(object, PurchaseDetailedList.class);
        purchaseDetailedList.setType(type);
        purchaseDetailedList.setUpdatetime(new Date());
        purchaseDetailedList.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
        try {
            purchaseDetailedListService.updateById(type, purchaseDetailedList.getId(), PrincipalUtil.getLoginUser().getId());
            String id = String.valueOf(purchaseDetailedList.getId());
            //根据子单与主单关联关系处理主单，如果查出来所有子单全部为结果确认，则将该主单类型置为结果确认，该状态意味着前台页面可以打印确认单
            QueryParams queryParams1 = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria1 = queryParams1.createCriteria();
            criteria1.andEqualTo("ssdd_glgx", purchaseDetailedList.getSsdd_glgx());
            List<PurchaseDetailedList> List1 = purchaseDetailedListService.selectListByParams(queryParams1);
            QueryParams queryParams = new QueryParams(PurchaseDetailedList.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("ssdd_glgx", purchaseDetailedList.getSsdd_glgx());
            criteria.andEqualTo("type", type);
            List<PurchaseDetailedList> List = purchaseDetailedListService.selectListByParams(queryParams);
            if (List.size() == List1.size()) {
                QueryParams queryParams2 = new QueryParams(PurchaseOrders.class);
                QueryParams.Criteria criteria2 = queryParams2.createCriteria();
                criteria2.andEqualTo("id", purchaseDetailedList.getSsdd_glgx());
                List<PurchaseOrders> ls = purchaseOrdersService.selectListByParams(queryParams2);
                PurchaseOrders lls = ls.get(0);
                lls.setType(type);
                lls.setUpdatetime(new Date());
                lls.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
                purchaseOrdersService.updateByPrimaryKey(lls);
            }
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("更新清单状态失败", e);
        }
        return pageInfo;
    }

    @Override
    public Map<String, String> updatePurchaseOrdersById4all_impl(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>(16);
        String object = request.getParameter("data");
        String type = request.getParameter("type");
        //更新主单
        PurchaseOrders purchaseOrders = JSONObject.parseObject(object, PurchaseOrders.class);
        purchaseOrders.setType(type);
        purchaseOrders.setUpdatetime(new Date());
        try {
            purchaseOrdersService.updateById(type, purchaseOrders.getId(), PrincipalUtil.getLoginUser().getId());
            Long id = purchaseOrders.getId();
            //更新所有子单ID
            purchaseDetailedListService.updateByParentId(type, purchaseOrders.getId(), PrincipalUtil.getLoginUser().getId());
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("更新采购单及其清单状态失败", e);
        }
        return pageInfo;
    }

    @Override
    public Map<String, String> updatePurchaseOrdersById_impl(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>(16);
        String object = request.getParameter("data");
        //更新主单
        PurchaseOrders purchaseOrders = JSONObject.parseObject(object, PurchaseOrders.class);
        purchaseOrders.setUpdatetime(new Date());
        purchaseOrders.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
        try {
            purchaseOrdersService.updateByPrimaryKey(purchaseOrders);
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("更新采购单失败", e);
        }
        return pageInfo;
    }

    @Override
    public Map<String, String> deletePurchaseOrdersById_impl(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>(16);
        String object = request.getParameter("data");
        //删除主单
        PurchaseOrders purchaseOrders = JSONObject.parseObject(object, PurchaseOrders.class);
        try {
            purchaseOrdersService.deleteByPrimaryKey(purchaseOrders.getId());
            pageInfo.put("status", "true");
        } catch (Exception e) {
            logger.error("删除采购单失败", e);
        }
        return pageInfo;
    }

    @Override
    public Map<String, String> toPassDetailByParentId_impl(HttpServletRequest request) {
        Map<String, String> pageInfo = new HashMap<String, String>(16);
        java.lang.String parentobject = request.getParameter("parentData");
        //先取到主单信息
        PurchaseOrders purchaseOrders = JSONObject.parseObject(parentobject, PurchaseOrders.class);
        purchaseOrders.setType("待审核");
        purchaseOrders.setUpdatetime(new Date());
        purchaseOrders.setUpdateuserid(PrincipalUtil.getLoginUser().getId());
        try {
            purchaseOrdersService.updateByPrimaryKey(purchaseOrders);
            //增加子单
            purchaseDetailedListService.updateByParentId("待审核", purchaseOrders.getId(), PrincipalUtil.getLoginUser().getId());
            //发送短信
            String context = purchaseOrders.getEntry_name() + "向您提交了一个新的采购单，请您尽快审阅审批！";
            ManageSendMessage manageSendMessage = new ManageSendMessage();
            try {
                manageSendMessage.queryMessage("采购办", PrincipalUtil.getLoginUser().getId(), context, sysUserService, systemProperties);
            } catch (Exception e) {
                logger.error("给采购办发送短信出错：{}", e.getMessage());
            }
            pageInfo.put("status", "true");

        } catch (Exception e) {
            logger.error("更新采购单及其清单状态失败", e);
        }
        return pageInfo;
    }

    /**
     * 购物车跳转到生成采购单界面
     *
     * @param request
     * @return
     */

    @Override
    @Transactional
    public Map<String, Object> establish(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<>(16);
        String product = request.getParameter("productInformation");
        String total = request.getParameter("total");
        List<OrderDetail> orderDetailList = JSON.parseArray(product, OrderDetail.class);
        Orders orders = new Orders();
        orders.setCreationTime(new Date());
        orders.setOrderNum(UUID.randomUUID().toString().replaceAll("-", ""));
        //刚生成订单
        orders.setOrderType("0");
        orders.setOrderInitiator(PrincipalUtil.getLoginUser().getId() + "");
        orders.setVersion(1L);
        try {
            orderMapper.insert(orders);
            //创建主单
            PurchaseOrders purchaseOrders = new PurchaseOrders();
            purchaseOrders.setType("申请");
            purchaseOrders.setCreator_userid(PrincipalUtil.getLoginUser().getId());
            if (PrincipalUtil.getLoginUser().getName() != null) {
                purchaseOrders.setCompany_name(PrincipalUtil.getLoginUser().getName());
            }
            purchaseOrders.setBhdget_amount(Float.valueOf(total));
            purchaseOrders.setLxr(PrincipalUtil.getLoginUser().getXmname());
            purchaseOrders.setPhone(PrincipalUtil.getLoginUser().getTelephone());
            purchaseOrders.setCreatetime(new Date());
            purchaseOrders.setSqdwfzr(PrincipalUtil.getLoginUser().getUsername());
            QueryParams queryParams = new QueryParams(BeginningBudget.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("userId", PrincipalUtil.getLoginUser().getId());
            List<BeginningBudget> beginningBudgets = beginningBudgetMapper.selectListByParams(queryParams);
            //年初预算金额
            if (beginningBudgets.size() > 0) {
                purchaseOrders.setCzbksr(beginningBudgets.get(0).getBudgetAmount().floatValue());
                //去年结余金额
                purchaseOrders.setQtsr(beginningBudgets.get(0).getBalanceAmount().floatValue());
            }
            purchaseOrders.setSqdwqmsj(new Date());
            purchaseOrders.setCgxs("政府集中采购");
            purchaseOrders.setWtdljg("社会代理机构");
            purchaseOrders.setZfcgfs("协议供货");
            purchaseOrdersMapper.insert(purchaseOrders);
            long f_id = purchaseOrders.getId();
            //拿到子单实体并创建子单
            for (OrderDetail orderDetail : orderDetailList) {
                orderDetail.setOrderId(orders.getId());
                PurchaseDetailedList purchaseDetailedList = new PurchaseDetailedList();
                purchaseDetailedList.setType("申请");
                purchaseDetailedList.setCreatetime(new Date());
                purchaseDetailedList.setSsdd_glgx(f_id);
                String[] strs = orderDetail.getCommodityType().split("-");
                purchaseDetailedList.setGoodsType(strs[0]);
                purchaseDetailedList.setOrderCarGlgx(String.valueOf(orderDetail.getId()));
                purchaseDetailedList.setCommodityId(orderDetail.getCommodityId());
                purchaseDetailedList.setDw(orderDetail.getUnit());
                if (orderDetail.getCommodityName() != null) {
                    purchaseDetailedList.setPmmc(orderDetail.getCommodityName());
                }
                if (orderDetail.getCommodityTrcPrc() != null) {
                    purchaseDetailedList.setDj(Float.valueOf(orderDetail.getCommodityTrcPrc()));
                }
                if (orderDetail.getCommodityNum() != null) {
                    purchaseDetailedList.setSl(Long.parseLong(orderDetail.getCommodityNum()));
                }
                if (orderDetail.getCommoditySplPrc() != null) {
                    purchaseDetailedList.setFinalPrice(Float.valueOf(orderDetail.getCommoditySplPrc()));
                }
                long commodityId = orderDetail.getCommodityId();
                String str = orderDetail.getCommodityType();
                String[] arrays = str.split("-");
                long m_id = Long.parseLong(arrays[arrays.length - 1]);
                //商品详情表查规格型号，技术参数
                Commodity commodity = commodityService.selectByPrimaryKey(commodityId);
                purchaseDetailedList.setGgxh(commodity.getModel());
                purchaseDetailedList.setJscs(commodity.getRests());
                purchaseDetailedList.setMerchantid(commodity.getBusinessesId());
                //meneu表查品目名称和编码
                Menu menu = menuServic.selectByPrimaryKey(m_id);
                purchaseDetailedList.setPmmc(menu.getName());
                purchaseDetailedList.setPmbm(menu.getCoding());
                purchaseDetailedList.setAstermap(orderDetail.getMasterMap());
                purchaseDetailedList.setZj(Float.valueOf(orderDetail.getCommodityTrcPrc()) * Long.parseLong(orderDetail.getCommodityNum()));
                purchaseDetailedList.setGoodsName(commodity.getCommodityName());
                purchaseDetailedList.setCreateuserid(PrincipalUtil.getLoginUser().getId());
                purchaseDetailedList.setCreatetime(new Date());
                purchaseDetailedListMapper.insert(purchaseDetailedList);
                orderDetailMapper.updateByPrimaryKey(orderDetail);
            }
            pageInfo.put("f_id", f_id);
            pageInfo.put("status", "true");
            pageInfo.put("purchaseOrders", purchaseOrders);
        } catch (Exception e) {
            logger.error("购物车申请采购失败", e);
        }

        return pageInfo;


    }

    @Override
    public void updateById(String type, long id, long c_userid) {
        purchaseOrdersMapper.updateById(type, id, c_userid);
    }

    /**
     * 修改年初预算信息数量
     * liuyun
     */

    public void modifyEarlyBudget(Long userId, String type, BigDecimal quantity) {
        QueryParams queryParams = new QueryParams(BeginningBudget.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("userId", userId);
        List<BeginningBudget> beginningBudgets = beginningBudgetMapper.selectListByParams(queryParams);
        if (beginningBudgets.size() > 0) {
            if ("++".equals(type)) {
                beginningBudgets.get(0).setBudgetAmount(beginningBudgets.get(0).getBudgetAmount().add(quantity));
            } else {
                beginningBudgets.get(0).setBudgetAmount(beginningBudgets.get(0).getBudgetAmount().subtract(quantity));
            }
            int i = beginningBudgetMapper.updateSelectiveByPrimaryKey(beginningBudgets.get(0));

        } else {
            logger.warn("修改年初预算信息时没有查询到该用户的年初预算信息！");
        }
    }
}
